package com.lsfb.signsys.view.BottomNavView;


import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.ColorStateList;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewCompat;
import android.support.v7.content.res.AppCompatResources;
import android.support.v7.view.SupportMenuInflater;
import android.support.v7.view.menu.MenuBuilder;
import android.support.v7.widget.TintTypedArray;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.lsfb.signsys.R;

/**
 * Created by zgscwjm on 2018/3/27.
 */

public class BottomNavView extends FrameLayout {

    /**
     * 启动颜色 和 禁用颜色
     */
    private static final int[] CHECKED_STATE_SET = {android.R.attr.state_checked};
    private static final int[] DISABLED_STATE_SET = {-android.R.attr.state_enabled};


    private final MenuBuilder mMenu;

    private final BottomNavigationMenuView mMenuView;

    private MenuInflater mMenuInflater;

    @SuppressLint("RestrictedApi")
    private final BottomNavigationPresenter mPresenter = new BottomNavigationPresenter();


    /**
     * 选择监听器
     */
    private BottomNavigationView.OnNavigationItemSelectedListener mSelectedListener;
    private BottomNavigationView.OnNavigationItemReselectedListener mReselectedListener;

    private static final int MENU_PRESENTER_ID = 1;

    public BottomNavView(@NonNull Context context) {
        this(context, null);
    }

    public BottomNavView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    @SuppressLint("RestrictedApi")
    public BottomNavView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        //这个只是对主题的检查
//        ThemeUtils.checkAppCompatTheme(context);

        //创建 菜单建造者
//        mMenu = new BottomNavigationMenu(context);
        mMenu = new BottomNavigationMenu(context);

        // 这个 是 菜单的view
        mMenuView = new BottomNavigationMenuView(context);

        //设置布局
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

        //居中
        params.gravity = Gravity.CENTER;

        //为菜单视图设置布局
        mMenuView.setLayoutParams(params);


        //将菜单视图放到 底部菜单导航 执行者里面
        mPresenter.setBottomNavigationMenuView(mMenuView);

        mPresenter.setId(MENU_PRESENTER_ID);

        //为菜单视图设置 执行者 典型的mvp模式
        mMenuView.setPresenter(mPresenter);

        //为菜单视图 设置 执行者
        mMenu.addMenuPresenter(mPresenter);


        //初始化 菜单
        mPresenter.initForMenu(getContext(),mMenu);

        // Custom attributes 自定义属性
        TintTypedArray a = TintTypedArray.obtainStyledAttributes(context, attrs,
                android.support.design.R.styleable.BottomNavigationView, defStyleAttr,
                android.support.design.R.style.Widget_Design_BottomNavigationView);


        TintTypedArray self_a = TintTypedArray.obtainStyledAttributes(context,attrs,R.styleable.BottomNavView);

        //设置图标

        if (self_a.getBoolean(R.styleable.BottomNavView_enableIconTint,false)) {
            if (a.hasValue(android.support.design.R.styleable.BottomNavigationView_itemIconTint)) {
                mMenuView.setIconTintList(
                        a.getColorStateList(android.support.design.R.styleable.BottomNavigationView_itemIconTint));
            } else {
                mMenuView.setIconTintList(
                        createDefaultColorStateList(android.R.attr.textColorSecondary));
            }
        }

        //设置文字颜色
        if (a.hasValue(android.support.design.R.styleable.BottomNavigationView_itemTextColor)) {
            mMenuView.setItemTextColor(
                    a.getColorStateList(android.support.design.R.styleable.BottomNavigationView_itemTextColor));
        } else {
            mMenuView.setItemTextColor(
                    createDefaultColorStateList(android.R.attr.textColorSecondary));
        }

        //设置 这个是阴影
        if (a.hasValue(android.support.design.R.styleable.BottomNavigationView_elevation)) {
            ViewCompat.setElevation(this, a.getDimensionPixelSize(
                    android.support.design.R.styleable.BottomNavigationView_elevation, 0));
        }

        //设置 背景颜色
        int itemBackground = a.getResourceId(android.support.design.R.styleable.BottomNavigationView_itemBackground, 0);
        mMenuView.setItemBackgroundRes(itemBackground);

        // 这里好像是 搞 菜单的
        if (a.hasValue(android.support.design.R.styleable.BottomNavigationView_menu)) {
            inflateMenu(a.getResourceId(android.support.design.R.styleable.BottomNavigationView_menu, 0));
        }


        if (self_a.hasValue(R.styleable.BottomNavView_shiftingModeSize)){
            mMenuView.setShiftingModeSize(self_a.getInt(R.styleable.BottomNavView_shiftingModeSize,4));
        }


        a.recycle();
        self_a.recycle();


        //添加 菜单view 到布局
        addView(mMenuView,params);

        //这个应该是分割线
        if (Build.VERSION.SDK_INT < 21) {
            addCompatibilityTopDivider(context);
        }

        //菜单单个实体 的回调事件
        mMenu.setCallback(new MenuBuilder.Callback() {
            @Override
            public boolean onMenuItemSelected(MenuBuilder menu, MenuItem item) {
                if (mReselectedListener != null && item.getItemId() == getSelectedItemId()) {
                    mReselectedListener.onNavigationItemReselected(item);
                    return true; // item is already selected
                }
                return mSelectedListener != null
                        && !mSelectedListener.onNavigationItemSelected(item);
            }

            @Override
            public void onMenuModeChange(MenuBuilder menu) {}
        });

    }

    /**
     * 添加分割线
     * @param context
     */
    private void addCompatibilityTopDivider(Context context) {
        View divider = new View(context);
        divider.setBackgroundColor(
                ContextCompat.getColor(context, android.support.design.R.color.design_bottom_navigation_shadow_color));
        FrameLayout.LayoutParams dividerParams = new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                getResources().getDimensionPixelSize(
                        android.support.design.R.dimen.design_bottom_navigation_shadow_height));
        divider.setLayoutParams(dividerParams);
        addView(divider);
    }


    /**
     * 返回 当前选中的菜单的id,如果返回0 说明没有菜单
     * @return
     */
    @SuppressLint("RestrictedApi")
    public int getSelectedItemId(){
        return mMenuView.getSelectedItemId();
    }

    /**
     * 实例化 菜单
     * @param resId
     */
    @SuppressLint("RestrictedApi")
    public void inflateMenu(int resId) {
        mPresenter.setUpdateSuspended(true);
        //从xml文件中解析menu 并添加到 mMenu 集合中
        getMenuInflater().inflate(resId, mMenu);
        mPresenter.setUpdateSuspended(false);
        mPresenter.updateMenuView(true);
    }


    //创建一个 菜单 inflater
    @SuppressLint("RestrictedApi")
    private MenuInflater getMenuInflater() {
        if (mMenuInflater == null) {
            mMenuInflater = new SupportMenuInflater(getContext());
        }
        return mMenuInflater;
    }
    /**
     * 这一坨是颜色选择
     * @param baseColorThemeAttr
     * @return
     */
    private ColorStateList createDefaultColorStateList(int baseColorThemeAttr) {
        final TypedValue value = new TypedValue();
        if (!getContext().getTheme().resolveAttribute(baseColorThemeAttr, value, true)) {
            return null;
        }
        ColorStateList baseColor = AppCompatResources.getColorStateList(
                getContext(), value.resourceId);
        if (!getContext().getTheme().resolveAttribute(
                android.support.v7.appcompat.R.attr.colorPrimary, value, true)) {
            return null;
        }
        int colorPrimary = value.data;
        int defaultColor = baseColor.getDefaultColor();
        return new ColorStateList(new int[][]{
                DISABLED_STATE_SET,
                CHECKED_STATE_SET,
                EMPTY_STATE_SET
        }, new int[]{
                baseColor.getColorForState(DISABLED_STATE_SET, defaultColor),
                colorPrimary,
                defaultColor
        });
    }


    /**
     * 设置item点击监听方法
     */
    public void setOnNavigationItemSelectedListener(@Nullable BottomNavigationView.OnNavigationItemSelectedListener onNavigationItemSelectedListener){
        this.mSelectedListener = onNavigationItemSelectedListener;
    }

    /**
     * 设置item释放监听
     * @param listener
     */
    public void setOnNavigationItemReselectedListener(
            @Nullable BottomNavigationView.OnNavigationItemReselectedListener listener) {
        mReselectedListener = listener;
    }

    @NonNull
    public Menu getMenu() {
        return mMenu;
    }

    public IBadge getBadge(int postion) {
        if (mMenuView==null){
            return null;
        }
        return mMenuView.getBadge(postion);
    }
}
